<template>
  <el-container>
    <el-aside width="auto">
      <el-menu class="el-menu-vertical"
               :default-active="$route.path"
               background-color="#2d3d59"
               text-color="#fff"
               active-text-color="#ffd04b"
               :collapse="isCollapse"
                router>

        <div class="logo">

        </div>
        <el-menu-item index="/AdminPage">
          <i class="el-icon-s-platform"></i>
          <span slot="title">首页</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-pie-chart"></i>
          <span slot="title">数据统计</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-s-order"></i>
          <span slot="title">订单管理</span>
        </el-menu-item>

        <el-submenu index="4">
          <template slot="title">
            <i class="el-icon-box"></i>
            <span slot="title">货物管理</span>
          </template>
          <el-menu-item-group>
            <el-menu-item class="group-2" index="/AdminCategory">分类管理</el-menu-item>
            <el-menu-item class="group-2" index="/AdminMerchandise">商品管理</el-menu-item>
          </el-menu-item-group>
        </el-submenu>

        <el-submenu v-if="auth" index="5">
          <template slot="title">
            <i class="el-icon-user-solid"></i>
            <span slot="title">人员管理</span>
          </template>
          <el-menu-item-group>
            <el-menu-item class="group-2" index="/AdminUser">用户管理</el-menu-item>
            <el-menu-item class="group-2" index="/AdminEmployee">员工管理</el-menu-item>
          </el-menu-item-group>
        </el-submenu>

        <el-submenu v-else disabled index="5">
          <template slot="title">
            <i class="el-icon-user-solid"></i>
            <span slot="title">人员管理</span>
          </template>
          <el-menu-item-group>
            <el-menu-item class="group-2" index="/AdminUser">用户管理</el-menu-item>
            <el-menu-item class="group-2" index="/AdminEmployee">员工管理</el-menu-item>
          </el-menu-item-group>
        </el-submenu>

        <el-submenu  v-if="auth" index="6">
          <template slot="title">
            <i class="el-icon-document"></i>
            <span slot="title">操作日志</span>
          </template>
          <el-menu-item-group>
            <el-menu-item class="group-2" index="/AdminOpLog">管理日志</el-menu-item>
           <el-menu-item class="group-2" index="6-2">系统日志</el-menu-item>
          </el-menu-item-group>
        </el-submenu>
        <el-submenu v-else disabled index="6">
          <template slot="title">
            <i class="el-icon-document"></i>
            <span slot="title">操作日志</span>
          </template>
          <el-menu-item-group>
          </el-menu-item-group>
        </el-submenu>

        <el-menu-item index="7">
          <i class="el-icon-document-copy"></i>
          <span slot="title">交互中心</span>
        </el-menu-item>

        <el-menu-item index="8">
          <i class="el-icon-chat-line-round"></i>
          <span slot="title">用户信息</span>
        </el-menu-item>

      </el-menu>
    </el-aside>
    <el-container class="bottom-container">
      <el-header class="header">
        <el-button type="text" @click="toggleCollapse" class="icon-button">
          <i
              :class="isCollapse ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
              class="icon-size"
          ></i>
        </el-button>
        <h1>橙子超市后台系统</h1>
        <div class="user-content">
          <button class="avatar-button" @click="drawer=true">
        <el-avatar
            alt="头像"
            shape="square"
            :src="avatarUrl"

        ><img
            src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"
            alt=""
        /></el-avatar>
          </button>
          <el-dropdown @command="handleCommand" show-timeout:100 hide-timeout:500>
            <el-button type="primary">
              {{username}}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <router-link to="AdminBroder"><el-dropdown-item command="a">首页</el-dropdown-item></router-link>
              <el-dropdown-item command="b">设置</el-dropdown-item>
              <el-dropdown-item command="c">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-main>

        <el-drawer
            title="后台设置（点击右上角或外侧区域关闭）"
            size="35%"

            :visible.sync="drawer"
            >

          <div class="drawer">
            <h2 style="text-align: center">相关状态设置</h2>
            <div class="shop-status">
              <el-card shadow="hover">
                <div class="shop-status-1">
                营业状态：<el-switch v-if="auth"
                  v-model="shopStatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="营业中"
                  inactive-text="已打烊">
              </el-switch>

                  <el-switch v-else disabled
                             v-model="shopStatus"
                             active-color="#13ce66"
                             inactive-color="#ff4949"
                             active-text="营业中"
                             inactive-text="已打烊">
                  </el-switch>
                </div>
                <br>
                <div class="shop-status-2">
                  前台消息：<el-switch
                    v-model="fontInfo"
                    active-text="接收"
                    inactive-text="屏蔽">
                </el-switch>
                </div>
                <br>

                <div class="shop-status-3">
                  <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-full-screen"
                  >
                    页面全屏
                  </el-button>
<!--                  <el-button
                      v-else
                      type="primary"
                      size="mini"
                      icon="el-icon-switch-button"
                      @click="toggleFullScreen"
                  >
                    关闭全屏
                  </el-button>-->
                </div>
              </el-card>
            </div>
            <h2 style="text-align: center">个人信息设置</h2>
          <div class="info-form">
            <el-card shadow="hover">
              <span style="text-align: center">修改个人信息</span>
          <el-form
              :model="infoForm"
              :rules="infoRules"
              ref="infoForm"
              label-width="100px"
              class="infoForm"
          >
            <el-form-item prop="avatarUrl" label="头像">
              <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="uploadAvatar"
                  >
                <img v-if="infoForm.avatarUrl" :src="infoForm.avatarUrl" class="avatar" alt="头像">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item prop="username" label="用户名">
              <el-input
                  v-model="infoForm.username"
                  maxlength="16"
                  show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
              <el-input
                  v-model="infoForm.phone"
                  minlength="11"
                  maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                  type="primary"
                  @click="submitInfoForm('infoForm')"
              >提交</el-button
              >
              <el-button @click="resetForm('infoForm')"
              >重置</el-button
              >
            </el-form-item>
          </el-form>
            </el-card>
          </div>
            <div class="password-form">
              <el-card shadow="hover">
                <span style="text-align: center">修改密码</span>
              <el-form
                  :model="passwordForm"
                  status-icon
                  :rules="rulePass"
                  ref="passwordForm"
                  label-width="100px"
                  class="demo-ruleForm"
              >
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input
                      type="password"
                      v-model="passwordForm.oldPassword"
                      auto-complete="off"
                      show-password
                      placeholder="请输入旧密码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                      type="password"
                      v-model="passwordForm.newPassword"
                      autocomplete="off"
                      show-password
                      placeholder="请输入新密码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                  <el-input
                      type="password"
                      v-model="passwordForm.checkPass"
                      autocomplete="off"
                      show-password
                      placeholder="请确认新密码"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                      type="primary"
                      @click="submitPasswordForm('passwordForm')"
                  >确定</el-button
                  >
                  <el-button @click="resetPwdForm"
                  >重置</el-button
                  >
                </el-form-item>
              </el-form>
              </el-card>
            </div>
          </div>
        </el-drawer>
        <transition name="fade">
            <router-view></router-view>
          </transition>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import axios from "@/api/axios";
import router from "@/router";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.passwordForm.checkPass !== "") {
          this.$refs.passwordForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      key: 0,

      isCollapse: false,
      auth: false,
      id:0,
      username:"",
      avatarUrl:"",
      centerDialogVisible:false,
      drawer: false,
      shopStatus:true,
      fontInfo:true,

      infoForm:{
        avatarUrl:"",
        username:"",
        phone:"",
      },

      passwordForm: {
        oldPassword: "",
        newPassword: "",
        checkPass: "",
      },

      infoRules:{
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            message: "用户名只能包含数字和英文字母(大小写)",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: "blur",
          },
          {
            min: 11,
            max: 11,
            message: "手机号码长度必须为11位",
            trigger: "blur",
          },
          {
            pattern: /^1\d{10}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
          {
            validator: this.noSpacesValidator,
            trigger: "blur",
          },
        ],
      },

      rulePass: {
        oldPassword: [
          {
            required: true,
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],

        newPassword: [
          { validator: validatePass, trigger: "blur" },
          {
            required: true,
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
        checkPass: [
          { validator: validatePass2, trigger: "blur" },
          {
            required: true,
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: this.noSpacesValidator, trigger: "blur" }, // 添加自定义验证器
        ],
      },
    }
  },

  mounted() {
    this.getUserContent();
    this.getAuthority();
    this.getUserSetContent();
  },

  methods:{
    refreshChild() {
      this.key += 1;
    },

    getUserSetContent(){
      axios.get("/admin/emp/set").then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.infoForm=response.data.data;
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    getUserContent(){
      this.id=localStorage.getItem("id");
      this.username=localStorage.getItem("username");
      this.avatarUrl=localStorage.getItem("avatarUrl");
    },
    getAuthority(){
      const params ={
        id:this.id,
      }
      axios.get("/admin/emp/auth",{params}).then((response) => {
        if(response.data.code ===0){
          this.$message.error(response.data.msg);
        }else if(response.data.data.authority===2){
          this.auth=true;
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    // handleOpen(key, keyPath) {
    //   console.log(key, keyPath);
    // },
    // handleClose(key, keyPath) {
    //   console.log(key, keyPath);
    // },
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    exit(){
      localStorage.removeItem("id");
      localStorage.removeItem("username");
      localStorage.removeItem("avatarUrl");
      localStorage.removeItem("jwt_token");
      router.push("/AdminLogin");
    },
    handleCommand(command){
      switch (command){
        case "a":
          break;
        case "b":
          this.drawer = true;
          break;
        case "c":
          this.exit();
          break;
      }
    },

    /*头像上传方法*/
    uploadAvatar(file) {
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.infoForm.avatarUrl=response.data.data;
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    noSpacesValidator(rule, value, callback) {
      if (value && typeof value === "string" && value.includes(" ")) {
        callback(new Error("不能包含空格"));
      } else {
        callback();
      }
    },

    /*提交修改个人信息表单*/
    submitInfoForm(){
      this.$refs["infoForm"].validate((valid) => {
        if (valid) {
          axios.post("/admin/emp/modify", this.infoForm).then((response) => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            } else {
              this.$message.success("修改成功");
              this.drawer = false;
              this.getUserSetContent();
            }
          }).catch((error) => {
            console.log(error);
          })
        } else {
          console.log("error submit!");
          return false;
        }
      })
    },



    /*提交修改密码表单*/
    submitPasswordForm() {
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          if (this.passwordForm.oldPassword === this.passwordForm.newPassword) {
            this.$message.warning("密码未更改！");
            return;
          }
          const formData = new FormData();
          formData.append("oldPassword", this.passwordForm.oldPassword);
          formData.append("newPassword", this.passwordForm.newPassword);
          axios.post("/admin/emp/password", formData).then((response) => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            } else {
              this.$message.success("修改成功");
              this.drawer = false;
            }
          }).catch((error) => {
            console.log(error);
          })
        } else {
          console.log("error submit!");
          return false;
        }
      })
    },

    /*重置个人信息*/
    resetForm() {
      this.getUserSetContent();
      this.$message.info("重置成功");
    },

    /*
     * 重置密码表单
     */
    resetPwdForm(){
      this.$refs.passwordForm.resetFields(this.passwordForm);
      this.$message.info("重置成功");
    }
    /*页面全屏控制*/
    // toggleFullScreen() {
    //   if (!this.isFullScreen) {
    //     this.enterFullScreen();
    //   } else {
    //     this.exitFullScreen();
    //   }
    //   this.isFullScreen = !this.isFullScreen;
    // },
    // enterFullScreen() {
    //   const docEl = document.documentElement;
    //   if (docEl.requestFullscreen) {
    //     docEl.requestFullscreen();
    //   } else if (docEl.mozRequestFullScreen) { // Firefox
    //     docEl.mozRequestFullScreen();
    //   } else if (docEl.webkitRequestFullScreen) { // Chrome, Safari, Opera
    //     docEl.webkitRequestFullScreen();
    //   } else if (docEl.msRequestFullscreen) { // IE/Edge
    //     docEl.msRequestFullscreen();
    //   }
    // },
    // exitFullScreen() {
    //   if (document.exitFullscreen) {
    //     document.exitFullscreen();
    //   } else if (document.mozCancelFullScreen) { // Firefox
    //     document.mozCancelFullScreen();
    //   } else if (document.webkitExitFullscreen) { // Chrome, Safari, Opera
    //     document.webkitExitFullscreen();
    //   } else if (document.msExitFullscreen) { // IE/Edge
    //     document.msExitFullscreen();
    //   }
    // }
  }
}
</script>

<style>

.fade-enter-active,

.fade-leave-active {

  transition: opacity 0.5s ease;

}

.fade-enter-from,

.fade-leave-active {

  opacity: 0;

}

/*侧边栏样式*/
.el-menu, .el-aside{
  background-color: #2d3d59;
}

.el-aside {
  height: 100vh; /* 设置侧边栏高度为屏幕高度 */
  overflow-y: auto; /* 如果内容超出屏幕高度,添加垂直滚动条 */
}

.logo{
  height: 60px;
  background-color: #f1f1f1;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.3);
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

/*头部和主页面的底部容器高度*/
.bottom-container{
  height: 100vh;
}

/*顶部样式*/
.el-header{
  height: 60px;
  background-color: #f1f1f1;
  display: flex;
  justify-content: space-between;
  box-shadow: 2px 4px 8px rgba(0, 0, 0, 0.3);
  z-index: 10; /* 设置较高的 z-index 值 */
}

.icon-button {
  font-size: 18px; /* 调整按钮的字体大小 */
}

.icon-size {
  font-size: 40px; /* 调整图标的大小 */
}

/*用户信息样式*/
.user-content{
  color:  #383d43;
  font-size: 20px;
  margin-top: 15px;
  margin-right: 50px;
}

.avatar-button {
  background-color: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.el-avatar{
  margin-right: 10px;
}

.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}

/*二级标签样式*/
.group-2{
  background-color: #3f4559 !important;
}

/*抽屉样式*/
.drawer{
  height: auto;
  background-color: rgb(237, 237, 237);
}

/*头像上传样式*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/*个人信息表单样式*/
.info-form{
  margin: 0 auto;
  width: 450px;
}

.shop-status{
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 450px;
}

.password-form{
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 450px;
}
</style>